//
//  PKConfigViewController.swift
//  Panku
//
//  Created by mac on 2017/2/13.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import YYKit
import SnapKit
import MessageUI
import SVProgressHUD

private let PKConfigViewControllerCellID = "PKConfigViewControllerCellID"

class PKConfigViewController: PKBaseViewController,UITableViewDataSource,UITableViewDelegate{

    
    //MARK: - init
    init(viewModel:PKConfigViewModel){
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    //MARK: - properties
    //viewModel
    var viewModel:PKConfigViewModel?
    
    lazy var logoutButton = PKBaseButton.createButton()

    lazy var tableView:PKBaseTableView = PKBaseTableView(frame: CGRect.zero, style: .grouped)
    
    //MARK: - life circle
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
    }
    
    //MARK: - UI
    override func setupRootView() {
        view.backgroundColor = UIColor.white
    }
    
    override func setupSubViews() {
        view.addSubview(tableView)
        tableView.addSubview(logoutButton)
    
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: PKConfigViewControllerCellID)

        logoutButton.addBlock(for: .touchUpInside) { (_) in
            PKLoginServices.deleteToken()
            self.navigationController!.popViewController(animated: true)
            
            SVProgressHUD.showSuccess(withStatus: "退出登录成功")
            PKDispatchUtils.delay(time: 0.3, block: {
                PKBaseTabBarController.sharedInstance!.selectedIndex = 0
            })
    
        }
        
        logoutButton.setTitleColor(UIColor.white, for: .normal)
        logoutButton.backgroundColor = UIColor.black
        logoutButton.layer.cornerRadius = 4
        logoutButton.layer.masksToBounds = true
        
        logoutButton.setTitle("退出登录", for: .normal)
    
    
    }
    
    override func setupSubViewsConstraints() {
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        logoutButton.frame = CGRect(x: 30, y: APP_HEIGHT-100-66-44, width: APP_WIDTH - 60, height: 44)
    }
        
    override func setupNavigationBar() {
        self.title = "设置"
    }
        
    override func bindViewModel() {
        
    }
}




extension PKConfigViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel!.numberOfSections()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel!.numberOfRowsInSection(section: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PKConfigViewControllerCellID, for: indexPath)
        
        //推送switch
        if indexPath == IndexPath(row: 1, section: 0) {
            let enbalePush = UISwitch()
            cell.accessoryView = enbalePush
        }else{
            cell.accessoryView = nil
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.textLabel?.text = viewModel?.titleForIndexPath(indexPath: indexPath)
//        cell.accessoryView =
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //设置deselect动画
        tableView.deselectRow(at: indexPath, animated: true)
        
        switch indexPath {
        case IndexPath(item: 0, section: 0)://账号与安全
            let accountSafetyController = PKAccountSafetyController(viewModel: viewModel!.viewModelForAccountSafetyController())
            self.navigationController?.pushViewController(accountSafetyController, animated: true)
            
        case IndexPath(item: 2, section: 0)://直播设置
            let liveConfigController = PKLiveConfigViewController(viewModel: viewModel!.viewModelForLiveConfigController())
            self.navigationController?.pushViewController(liveConfigController, animated: true)
        case IndexPath(item: 3, section: 0)://黑名单
            //TODO:打开黑名单
            break
        case IndexPath(item: 0, section: 1)://清理缓存
            //TODO:清理缓存
            break
        case IndexPath(item: 0, section: 3)://帮助与反馈
            //TODO:打开帮助与反馈
            let emailController = MFMailComposeViewController()
            emailController.mailComposeDelegate = self
            emailController.setSubject("放克app意见反馈")
            emailController.setMessageBody("Hello there", isHTML: false)
            emailController.setToRecipients([PKConfigServices.feedbackEmailAddress()])
            self.present(emailController, animated: true, completion: { 
                
            })
            break
        case IndexPath(item: 1, section: 3)://关于我们
            let aboutUsController = PKAboutUsViewController()
            self.navigationController?.pushViewController(aboutUsController, animated: true)
            break
        default:
            print("")
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
}

extension PKConfigViewController:MFMailComposeViewControllerDelegate{
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        
        if error == nil{
            switch result {
            case .cancelled:
                SVProgressHUD.showInfo(withStatus: "取消发送邮件")
            case .saved:
                SVProgressHUD.showInfo(withStatus: "邮件草稿保存")
            case .sent:
                SVProgressHUD.showSuccess(withStatus: "成功发送邮件")
            case .failed:
                SVProgressHUD.showError(withStatus: "发送邮件失败")
            }
            
        }else{
            SVProgressHUD.showError(withStatus: "发送邮件失败")
        }
        controller.dismiss(animated: true) { 
            
        }
    }
}
